package com.jz.digital.dialog;

import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDialog;
import androidx.fragment.app.FragmentActivity;

import com.jz.digital.R;
import com.jz.digital.base.BaseDialogFragment;
import com.jz.digital.utils.DipPixelUtil;
import com.jz.digital.utils.WindowUtil;

/**
 * Copyright (c) 2019 深圳市爱都科技有限公司. All rights reserved.
 *
 * @Author: xyb
 * @CreateDate: 2019-12-28 16:02
 * @description
 */
public class WaitingDialog extends BaseDialogFragment {
    private static final String TAG = "WaitingDialog";
    private static final String INTENT_EXTRA_MESSAGE = "intent_extra_message";
    private static final String INTENT_EXTRA_CANCELABLE = "intent_extra_cancelable";
    private static WaitingDialog sWaitingDialog = null;

    private TextView waitingMessageTv;

    public static WaitingDialog newInstance() {
        return newInstance(null);
    }

    public static WaitingDialog newInstance(String message) {
        return newInstance(message, true);
    }

    public static WaitingDialog newInstance(String message, boolean cancelable) {
        WaitingDialog waitingDialog = new WaitingDialog();
        Bundle arguments = new Bundle();
        arguments.putBoolean(INTENT_EXTRA_CANCELABLE, cancelable);
        if (!TextUtils.isEmpty(message)) {
            arguments.putString(INTENT_EXTRA_MESSAGE, message);
        }
        waitingDialog.setArguments(arguments);
        return waitingDialog;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getDialog() != null && getDialog().getWindow() != null) {
            getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                    WindowUtil.getWindowSize(getContext()).getHeight() - DipPixelUtil.dip2px(100));
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        String message = "";
        boolean cancelable = false;
        if (arguments != null) {
            message = arguments.getString(INTENT_EXTRA_MESSAGE, "");
            cancelable = arguments.getBoolean(INTENT_EXTRA_CANCELABLE);
        }
        AppCompatDialog progressDialog = new AppCompatDialog(getActivity(), R.style.TransparentStyle);
        progressDialog.setContentView(R.layout.dialog_waiting);
        waitingMessageTv = progressDialog.findViewById(R.id.waiting_tv);
        if (waitingMessageTv != null) {
            waitingMessageTv.setText(message);
            waitingMessageTv.setVisibility(TextUtils.isEmpty(message) ? View.GONE : View.VISIBLE);
        }

        progressDialog.setCanceledOnTouchOutside(false);//点击外部不会消失
        setBackToActivity(cancelable);
        backToActivity(progressDialog, cancelable);
        if (getActivity() != null) {
            getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
        }
        return progressDialog;
    }

    /**
     * 监听返回键并回调activity的back键方法
     *
     * @param progressDialog
     * @param cancelable
     */
    private void backToActivity(AppCompatDialog progressDialog, boolean cancelable) {
        progressDialog.setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (mIsBackToActivity && getActivity() != null) {
                    getActivity().onBackPressed();
                }
                return !cancelable;
            } else {
                return true;
            }
        });
    }

    private boolean mIsBackToActivity = true;//按返回键是否回调activity的back键方法

    /**
     * 设置是否监听按键事件并在按下返回键时回调activity的back键方法
     *
     * @param isBack true or false
     */
    public void setBackToActivity(boolean isBack) {
        this.mIsBackToActivity = isBack;
    }

    public void updateMessage(String message) {
        if (waitingMessageTv == null) return;
        waitingMessageTv.setText(message);
        waitingMessageTv.setVisibility(TextUtils.isEmpty(message) ? View.GONE : View.VISIBLE);
    }

    /**
     * 对话框弹出后按返回键不消失;
     *
     * @param activity
     */
    public static void showDialogUncancel(FragmentActivity activity) {
        showDialog(activity, false, null);
    }

    public static void showDialogUncancel(FragmentActivity activity, String message) {
        showDialog(activity, false, message);
    }

    /**
     * 对话框弹出后按返回键会消失;
     *
     * @param activity
     */
    public static void showDialog(FragmentActivity activity) {
        showDialog(activity, true, null);
    }

    public static void showDialog(FragmentActivity activity, String message) {
        showDialog(activity, true, message);
    }

    /**
     * 对话框弹出后按返回键消失且会执行其获取的activity的onBackPressed()方法
     *
     * @param activity
     */
    public static void showDialogBack(FragmentActivity activity) {
        showDialog(activity, true, null);
        sWaitingDialog.setBackToActivity(true);
    }

    public static void showDialogBack(FragmentActivity activity, String message) {
        showDialog(activity, true, message);
        sWaitingDialog.setBackToActivity(true);
    }

    private static void showDialog(FragmentActivity activity, boolean cancelAble, String message) {
        if (!isShowing()) {
            sWaitingDialog = newInstance(message);
            sWaitingDialog.setCancelable(cancelAble);
            sWaitingDialog.show(activity.getSupportFragmentManager());
        }
    }

    public static void hideDialog() {
        //CommonLogUtil.d(TAG, "hideDialog: " + sWaitingDialog + ","+sWaitingDialog.getFragmentManager());
        if (sWaitingDialog != null && sWaitingDialog.getFragmentManager() != null) {
            sWaitingDialog.dismissAllowingStateLoss();
        }
    }

    public static void hideDialogDelay(long delay) {
        new Handler().postDelayed(WaitingDialog::hideDialog, delay);
    }

    public static boolean isShowing() {
        return sWaitingDialog != null
                && sWaitingDialog.getDialog() != null
                && sWaitingDialog.getDialog().isShowing();
    }

    public void setBackgroundDrawable(Drawable drawable) {
        if (getDialog() != null) {
            RelativeLayout dialogLayout = getDialog().findViewById(R.id.rlLayout);
            if (dialogLayout != null && drawable != null) {
                dialogLayout.setBackground(drawable);
            }
        }
    }
}
